import requests
from bs4 import BeautifulSoup
import json
from django.http import HttpResponse

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    lis = soup.select("#dvLoad .list-group-item")

    for li in lis:
        tempData = resultData()
        try:
            tempData["titleHref"] = 'http://ruc.tokyotrial.net'+li.select(".aNoC")[0]["href"]
        except:
            pass
        try:
            tempData["publishTime"] = [li.select(".aCrs")[0].text.strip()]
        except:
            pass
        try:
            tempData["source"] = li.select(".badge")[0].text.strip() +'|'+ li.select(".badge")[1].text.strip()
        except:
            pass
        try:
            tempData["summary"] = li.select(".list-group-item-text")[0].text.strip()
        except:
            pass

        allData.append(tempData)

    return allData

def getData(keyword):
    headers = {
        'Proxy-Connection': 'keep-alive',
        'Pragma': 'no-cache',
        'Cache-Control': 'no-cache',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',
        'Accept': '*/*',
        'Referer': 'http://ruc.tokyotrial.net/Tookit/bootstrap/assets/css/font-awesome.css',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Origin': 'http://ruc.tokyotrial.net',
    }
    params = (
        ('sn', keyword),
        ('type', '9'),
        ('mode', '0'),
    )

    response = requests.get('http://ruc.tokyotrial.net/Resource', headers=headers, params=params)

    allData = formData(response)

    return allData


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    allData= getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")